import React, { useState, useEffect } from 'react';
import { createDomainWithWizard, checkDomainName, getHostResources, listStoragePools, listNetworks } from '../api/client';
import './CreateVMWizardV2.css';

interface CreateVMWizardV2Props {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (vm: any) => void;
}

// 创建方法枚举
type CreateMethod = 'local_iso' | 'network' | 'import_disk' | 'manual';

interface VMFormData {
  // 创建方法选择
  method: CreateMethod;

  // 基本信息
  name: string;
  description: string;
  osType: string;
  osVersion: string;

  // 资源配置
  vcpus: number;
  memory: number;
  memoryUnit: 'MB' | 'GB';
  cpuModel: string;

  // 存储配置
  storagePool: string;
  diskSize: number;
  diskFormat: string;
  diskBus: string;
  cacheMode: string;

  // 网络配置
  networkType: string;
  networkName: string;
  networkModel: string;
  macAddress: string;

  // 启动选项
  bootOrder: string[];
  autostart: boolean;
  bootDelay: number;
  loader: string;
  graphics: string;
  displayProtocol: string;

  // 本地ISO配置
  localIsoPath: string;
  localIsoCdrom: boolean;

  // 网络安装配置
  networkSource: string;
  networkKernel: string;
  networkInitrd: string;
  networkExtra: string;

  // 磁盘导入配置
  importDiskPath: string;
  importCopy: boolean;

  // 手动创建配置
  customXml: string;
}

const CreateVMWizardV2: React.FC<CreateVMWizardV2Props> = ({ isOpen, onClose, onSuccess }) => {
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState<VMFormData>({
    // 默认值
    method: 'local_iso',
    name: '',
    description: '',
    osType: 'linux',
    osVersion: 'ubuntu22.04',
    vcpus: 2,
    memory: 2048,
    memoryUnit: 'MB',
    cpuModel: 'host-model',
    storagePool: 'default',
    diskSize: 20,
    diskFormat: 'qcow2',
    diskBus: 'virtio',
    cacheMode: 'writeback',
    networkType: 'nat',
    networkName: 'default',
    networkModel: 'virtio',
    macAddress: '',
    bootOrder: ['cdrom', 'hd'],
    autostart: false,
    bootDelay: 0,
    loader: 'uefi',
    graphics: 'vnc',
    displayProtocol: 'vnc',
    localIsoPath: '',
    localIsoCdrom: true,
    networkSource: '',
    networkKernel: '',
    networkInitrd: '',
    networkExtra: '',
    importDiskPath: '',
    importCopy: false,
    customXml: ''
  });

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [hostResources, setHostResources] = useState<any>(null);
  const [storagePools, setStoragePools] = useState<any[]>([]);
  const [networks, setNetworks] = useState<any[]>([]);
  const [nameAvailable, setNameAvailable] = useState<boolean | null>(null);
  const [isCheckingName, setIsCheckingName] = useState(false);

  // const totalSteps = 6; // 增加了方法选择步骤

  // 根据创建方法确定实际步骤数
  const getActualSteps = () => {
    switch (formData.method) {
      case 'local_iso':
        return 6; // 方法选择 + 基本信息 + 资源配置 + 存储配置 + 网络配置 + 启动选项
      case 'network':
        return 7; // 方法选择 + 基本信息 + 资源配置 + 网络安装配置 + 存储配置 + 网络配置 + 启动选项
      case 'import_disk':
        return 6; // 方法选择 + 基本信息 + 资源配置 + 磁盘导入配置 + 网络配置 + 启动选项
      case 'manual':
        return 3; // 方法选择 + 基本信息 + 自定义XML
      default:
        return 6;
    }
  };

  // 加载初始化数据
  useEffect(() => {
    if (isOpen) {
      loadInitialData();
      generateMACAddress();
    }
  }, [isOpen]);

  // 检查名称可用性
  useEffect(() => {
    if (formData.name.trim()) {
      checkNameAvailability(formData.name.trim());
    } else {
      setNameAvailable(null);
    }
  }, [formData.name]);

  const loadInitialData = async () => {
    try {
      const [resourcesRes, poolsRes, networksRes] = await Promise.all([
        getHostResources(),
        listStoragePools(),
        listNetworks()
      ]);

      setHostResources(resourcesRes.data);
      setStoragePools(poolsRes.data.pools || []);
      setNetworks(networksRes.data.networks || []);
    } catch (error) {
      console.error('Failed to load initial data:', error);
    }
  };

  const generateMACAddress = () => {
    const mac = '52:54:00' + Array.from({length: 3}, () =>
      Math.floor(Math.random() * 256).toString(16).padStart(2, '0')
    ).join(':');
    setFormData(prev => ({ ...prev, macAddress: mac }));
  };

  const checkNameAvailability = async (name: string) => {
    setIsCheckingName(true);
    try {
      const response = await checkDomainName(name);
      setNameAvailable(response.data.available);
    } catch (error) {
      setNameAvailable(false);
    } finally {
      setIsCheckingName(false);
    }
  };

  const handleNext = () => {
    if (validateCurrentStep()) {
      if (currentStep < getActualSteps()) {
        setCurrentStep(currentStep + 1);
      } else {
        handleSubmit();
      }
    }
  };

  const handlePrevious = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const validateCurrentStep = (): boolean => {
    const newErrors: Record<string, string> = {};

    switch (currentStep) {
      case 1: // 方法选择
        if (!formData.method) {
          newErrors.method = '请选择创建方法';
        }
        break;

      case 2: // 基本信息
        if (!formData.name.trim()) {
          newErrors.name = '虚拟机名称不能为空';
        } else if (!/^[a-zA-Z0-9_-]+$/.test(formData.name)) {
          newErrors.name = '名称只能包含字母、数字、下划线和连字符';
        } else if (nameAvailable === false) {
          newErrors.name = '该名称已被使用';
        }
        if (!formData.osType) {
          newErrors.osType = '请选择操作系统类型';
        }
        break;

      case 3: // 资源配置
        if (formData.vcpus < 1 || formData.vcpus > 128) {
          newErrors.vcpus = 'CPU核心数必须在1-128之间';
        }
        if (formData.memory < 512) {
          newErrors.memory = '内存不能小于512MB';
        }
        if (hostResources && formData.memory > hostResources.memory.total * 0.8) {
          newErrors.memory = '内存不能超过宿主机总内存的80%';
        }
        break;

      case 4: // 特定方法配置
        switch (formData.method) {
          case 'local_iso':
            if (!formData.localIsoPath.trim()) {
              newErrors.localIsoPath = '请选择ISO文件路径';
            }
            break;
          case 'network':
            if (!formData.networkSource.trim()) {
              newErrors.networkSource = '请填写网络安装源URL';
            }
            break;
          case 'import_disk':
            if (!formData.importDiskPath.trim()) {
              newErrors.importDiskPath = '请选择要导入的磁盘映像路径';
            }
            break;
        }
        break;

      case 5: // 存储配置（适用于local_iso和network）
        if (formData.method === 'local_iso' || formData.method === 'network') {
          if (formData.diskSize < 1) {
            newErrors.diskSize = '磁盘大小必须大于0';
          }
        }
        break;

      case 6: // 网络配置（适用于local_iso和import_disk）
        if (formData.method === 'local_iso' || formData.method === 'import_disk') {
          if (formData.networkType === 'network' && !formData.networkName) {
            newErrors.networkName = '请选择虚拟网络';
          }
        }
        break;

      case 7: // 启动选项（适用于local_iso和network）
        // 启动选项验证
        break;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validateCurrentStep()) {
      return;
    }

    setIsSubmitting(true);
    try {
      // 构建向导规格
      const wizardSpec = {
        method: formData.method,
        name: formData.name,
        description: formData.description,
        osType: formData.osType,
        osVersion: formData.osVersion,
        vcpus: formData.vcpus,
        memory: formData.memory,
        memoryUnit: formData.memoryUnit,
        cpuModel: formData.cpuModel,
        storagePool: formData.storagePool,
        diskSize: formData.diskSize,
        diskFormat: formData.diskFormat,
        diskBus: formData.diskBus,
        cacheMode: formData.cacheMode,
        networkType: formData.networkType,
        networkName: formData.networkName,
        networkModel: formData.networkModel,
        macAddress: formData.macAddress,
        bootOrder: formData.bootOrder,
        autostart: formData.autostart,
        bootDelay: formData.bootDelay,
        loader: formData.loader,
        graphics: formData.graphics,
        displayProtocol: formData.displayProtocol,
        local_iso_path: formData.localIsoPath,
        local_iso_cdrom: formData.localIsoCdrom,
        network_source: formData.networkSource,
        network_kernel: formData.networkKernel,
        network_initrd: formData.networkInitrd,
        network_extra: formData.networkExtra,
        import_disk_path: formData.importDiskPath,
        import_copy: formData.importCopy,
        custom_xml: formData.customXml
      };

      // 使用新的向导API
      const response = await createDomainWithWizard(wizardSpec);
      onSuccess(response.data);
      onClose();
    } catch (error: any) {
      console.error('Failed to create VM:', error);
      setErrors({ submit: error.response?.data?.detail || '创建虚拟机失败' });
    } finally {
      setIsSubmitting(false);
    }
  };

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="step-content">
            <h3>选择创建方法</h3>
            <div className="method-selection">
              <div className="method-option">
                <input
                  type="radio"
                  id="local_iso"
                  name="method"
                  value="local_iso"
                  checked={formData.method === 'local_iso'}
                  onChange={(e) => setFormData({ ...formData, method: e.target.value as CreateMethod })}
                />
                <label htmlFor="local_iso">
                  <strong>从本地ISO创建</strong>
                  <p>使用本地ISO文件安装操作系统，支持CD-ROM设备配置和启动顺序设置</p>
                </label>
              </div>

              <div className="method-option">
                <input
                  type="radio"
                  id="network"
                  name="method"
                  value="network"
                  checked={formData.method === 'network'}
                  onChange={(e) => setFormData({ ...formData, method: e.target.value as CreateMethod })}
                />
                <label htmlFor="network">
                  <strong>从网络安装创建</strong>
                  <p>通过网络安装源（HTTP/FTP）安装操作系统，支持网络引导和内核参数配置</p>
                </label>
              </div>

              <div className="method-option">
                <input
                  type="radio"
                  id="import_disk"
                  name="method"
                  value="import_disk"
                  checked={formData.method === 'import_disk'}
                  onChange={(e) => setFormData({ ...formData, method: e.target.value as CreateMethod })}
                />
                <label htmlFor="import_disk">
                  <strong>从磁盘映像导入</strong>
                  <p>导入现有的磁盘映像文件，支持磁盘挂载和启动参数配置</p>
                </label>
              </div>

              <div className="method-option">
                <input
                  type="radio"
                  id="manual"
                  name="method"
                  value="manual"
                  checked={formData.method === 'manual'}
                  onChange={(e) => setFormData({ ...formData, method: e.target.value as CreateMethod })}
                />
                <label htmlFor="manual">
                  <strong>手动创建</strong>
                  <p>完全自定义虚拟机配置，支持直接编辑XML配置</p>
                </label>
              </div>
            </div>
            {errors.method && <span className="error">{errors.method}</span>}
          </div>
        );

      case 2:
        return (
          <div className="step-content">
            <h3>基本信息</h3>
            <div className="form-group">
              <label>虚拟机名称 *</label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="输入虚拟机名称"
              />
              {isCheckingName && <span>检查名称中...</span>}
              {nameAvailable === true && <span className="success">✓ 名称可用</span>}
              {nameAvailable === false && <span className="error">✗ 名称已被使用</span>}
              {errors.name && <span className="error">{errors.name}</span>}
            </div>

            <div className="form-group">
              <label>描述</label>
              <textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="虚拟机描述（可选）"
                rows={3}
              />
            </div>

            <div className="form-group">
              <label>操作系统类型 *</label>
              <select
                value={formData.osType}
                onChange={(e) => setFormData({ ...formData, osType: e.target.value })}
              >
                <option value="linux">Linux</option>
                <option value="windows">Windows</option>
                <option value="other">其他</option>
              </select>
              {errors.osType && <span className="error">{errors.osType}</span>}
            </div>
          </div>
        );

      case 3:
        return (
          <div className="step-content">
            <h3>资源配置</h3>
            <div className="form-group">
              <label>CPU核心数 *</label>
              <input
                type="number"
                min="1"
                max="128"
                value={formData.vcpus}
                onChange={(e) => setFormData({ ...formData, vcpus: parseInt(e.target.value) || 1 })}
              />
              {errors.vcpus && <span className="error">{errors.vcpus}</span>}
            </div>

            <div className="form-group">
              <label>内存大小 *</label>
              <div className="input-group">
                <input
                  type="number"
                  min="512"
                  value={formData.memory}
                  onChange={(e) => setFormData({ ...formData, memory: parseInt(e.target.value) || 512 })}
                />
                <select
                  value={formData.memoryUnit}
                  onChange={(e) => setFormData({ ...formData, memoryUnit: e.target.value as 'MB' | 'GB' })}
                >
                  <option value="MB">MB</option>
                  <option value="GB">GB</option>
                </select>
              </div>
              {errors.memory && <span className="error">{errors.memory}</span>}
            </div>

            <div className="form-group">
              <label>CPU模式</label>
              <select
                value={formData.cpuModel}
                onChange={(e) => setFormData({ ...formData, cpuModel: e.target.value })}
              >
                <option value="host-model">Host Model</option>
                <option value="host-passthrough">Host Passthrough</option>
                <option value="custom">自定义</option>
              </select>
            </div>
          </div>
        );

      case 4:
        // 根据方法显示不同的配置
        switch (formData.method) {
          case 'local_iso':
            return (
              <div className="step-content">
                <h3>本地ISO配置</h3>
                <div className="form-group">
                  <label>ISO文件路径 *</label>
                  <input
                    type="text"
                    value={formData.localIsoPath}
                    onChange={(e) => setFormData({ ...formData, localIsoPath: e.target.value })}
                    placeholder="/path/to/iso/file.iso"
                  />
                  {errors.localIsoPath && <span className="error">{errors.localIsoPath}</span>}
                </div>

                <div className="form-group">
                  <label>
                    <input
                      type="checkbox"
                      checked={formData.localIsoCdrom}
                      onChange={(e) => setFormData({ ...formData, localIsoCdrom: e.target.checked })}
                    />
                    使用CD-ROM设备
                  </label>
                  <small>启用此选项将添加CD-ROM设备用于ISO引导</small>
                </div>
              </div>
            );

          case 'network':
            return (
              <div className="step-content">
                <h3>网络安装配置</h3>
                <div className="form-group">
                  <label>安装源URL *</label>
                  <input
                    type="text"
                    value={formData.networkSource}
                    onChange={(e) => setFormData({ ...formData, networkSource: e.target.value })}
                    placeholder="http://example.com/install/"
                  />
                  {errors.networkSource && <span className="error">{errors.networkSource}</span>}
                </div>

                <div className="form-group">
                  <label>内核路径</label>
                  <input
                    type="text"
                    value={formData.networkKernel}
                    onChange={(e) => setFormData({ ...formData, networkKernel: e.target.value })}
                    placeholder="/path/to/kernel"
                  />
                </div>

                <div className="form-group">
                  <label>Initrd路径</label>
                  <input
                    type="text"
                    value={formData.networkInitrd}
                    onChange={(e) => setFormData({ ...formData, networkInitrd: e.target.value })}
                    placeholder="/path/to/initrd"
                  />
                </div>

                <div className="form-group">
                  <label>额外内核参数</label>
                  <input
                    type="text"
                    value={formData.networkExtra}
                    onChange={(e) => setFormData({ ...formData, networkExtra: e.target.value })}
                    placeholder="console=ttyS0"
                  />
                </div>
              </div>
            );

          case 'import_disk':
            return (
              <div className="step-content">
                <h3>磁盘导入配置</h3>
                <div className="form-group">
                  <label>磁盘映像路径 *</label>
                  <input
                    type="text"
                    value={formData.importDiskPath}
                    onChange={(e) => setFormData({ ...formData, importDiskPath: e.target.value })}
                    placeholder="/path/to/disk.qcow2"
                  />
                  {errors.importDiskPath && <span className="error">{errors.importDiskPath}</span>}
                </div>

                <div className="form-group">
                  <label>
                    <input
                      type="checkbox"
                      checked={formData.importCopy}
                      onChange={(e) => setFormData({ ...formData, importCopy: e.target.checked })}
                    />
                    复制磁盘文件
                  </label>
                  <small>启用此选项将在存储池中创建磁盘副本</small>
                </div>
              </div>
            );

          case 'manual':
            return (
              <div className="step-content">
                <h3>自定义XML配置</h3>
                <div className="form-group">
                  <label>XML配置 *</label>
                  <textarea
                    value={formData.customXml}
                    onChange={(e) => setFormData({ ...formData, customXml: e.target.value })}
                    placeholder="&lt;domain type='kvm'&gt;...&lt;/domain&gt;"
                    rows={15}
                    style={{ fontFamily: 'monospace', fontSize: '12px' }}
                  />
                  {errors.customXml && <span className="error">{errors.customXml}</span>}
                </div>
              </div>
            );

          default:
            return null;
        }

      // 存储配置步骤
      case 5:
        if (formData.method === 'local_iso' || formData.method === 'network') {
          return (
            <div className="step-content">
              <h3>存储配置</h3>
              <div className="form-group">
                <label>存储池</label>
                <select
                  value={formData.storagePool}
                  onChange={(e) => setFormData({ ...formData, storagePool: e.target.value })}
                >
                  {storagePools.map((pool: any) => (
                    <option key={pool.name} value={pool.name}>{pool.name}</option>
                  ))}
                </select>
              </div>

              <div className="form-group">
                <label>磁盘大小 (GB)</label>
                <input
                  type="number"
                  min="1"
                  value={formData.diskSize}
                  onChange={(e) => setFormData({ ...formData, diskSize: parseInt(e.target.value) || 1 })}
                />
                {errors.diskSize && <span className="error">{errors.diskSize}</span>}
              </div>

              <div className="form-group">
                <label>磁盘格式</label>
                <select
                  value={formData.diskFormat}
                  onChange={(e) => setFormData({ ...formData, diskFormat: e.target.value })}
                >
                  <option value="qcow2">QCOW2</option>
                  <option value="raw">RAW</option>
                </select>
              </div>

              <div className="form-group">
                <label>磁盘总线</label>
                <select
                  value={formData.diskBus}
                  onChange={(e) => setFormData({ ...formData, diskBus: e.target.value })}
                >
                  <option value="virtio">VirtIO</option>
                  <option value="ide">IDE</option>
                  <option value="scsi">SCSI</option>
                </select>
              </div>

              <div className="form-group">
                <label>缓存模式</label>
                <select
                  value={formData.cacheMode}
                  onChange={(e) => setFormData({ ...formData, cacheMode: e.target.value })}
                >
                  <option value="writeback">Writeback</option>
                  <option value="writethrough">Writethrough</option>
                  <option value="none">None</option>
                </select>
              </div>
            </div>
          );
        }
        // 对于其他方法，跳过此步骤
        return null;

      // 网络配置步骤
      case 6:
        if (formData.method === 'local_iso' || formData.method === 'import_disk') {
          return (
            <div className="step-content">
              <h3>网络配置</h3>
              <div className="form-group">
                <label>网络类型</label>
                <select
                  value={formData.networkType}
                  onChange={(e) => setFormData({ ...formData, networkType: e.target.value })}
                >
                  <option value="nat">NAT</option>
                  <option value="bridge">桥接</option>
                  <option value="host">主机网络</option>
                </select>
              </div>

              {formData.networkType === 'nat' && (
                <div className="form-group">
                  <label>虚拟网络</label>
                  <select
                    value={formData.networkName}
                    onChange={(e) => setFormData({ ...formData, networkName: e.target.value })}
                  >
                    {networks.map((network: any) => (
                      <option key={network.name} value={network.name}>{network.name}</option>
                    ))}
                  </select>
                  {errors.networkName && <span className="error">{errors.networkName}</span>}
                </div>
              )}

              <div className="form-group">
                <label>网络模型</label>
                <select
                  value={formData.networkModel}
                  onChange={(e) => setFormData({ ...formData, networkModel: e.target.value })}
                >
                  <option value="virtio">VirtIO</option>
                  <option value="e1000">E1000</option>
                  <option value="rtl8139">RTL8139</option>
                </select>
              </div>

              <div className="form-group">
                <label>MAC地址</label>
                <input
                  type="text"
                  value={formData.macAddress}
                  onChange={(e) => setFormData({ ...formData, macAddress: e.target.value })}
                  placeholder="52:54:00:XX:XX:XX"
                />
                <button onClick={generateMACAddress} style={{ marginLeft: '8px' }}>生成</button>
                {errors.macAddress && <span className="error">{errors.macAddress}</span>}
              </div>
            </div>
          );
        }
        // 对于其他方法，跳过此步骤
        return null;

      // 启动选项步骤
      case 7:
        if (formData.method === 'local_iso' || formData.method === 'network') {
          return (
            <div className="step-content">
              <h3>启动选项</h3>
              <div className="form-group">
                <label>启动顺序</label>
                <div className="checkbox-group">
                  <label>
                    <input
                      type="checkbox"
                      checked={formData.bootOrder.includes('cdrom')}
                      onChange={(e) => {
                        const newOrder = e.target.checked
                          ? [...formData.bootOrder, 'cdrom']
                          : formData.bootOrder.filter(item => item !== 'cdrom');
                        setFormData({ ...formData, bootOrder: newOrder });
                      }}
                    />
                    CD-ROM
                  </label>
                  <label>
                    <input
                      type="checkbox"
                      checked={formData.bootOrder.includes('hd')}
                      onChange={(e) => {
                        const newOrder = e.target.checked
                          ? [...formData.bootOrder, 'hd']
                          : formData.bootOrder.filter(item => item !== 'hd');
                        setFormData({ ...formData, bootOrder: newOrder });
                      }}
                    />
                    硬盘
                  </label>
                  <label>
                    <input
                      type="checkbox"
                      checked={formData.bootOrder.includes('network')}
                      onChange={(e) => {
                        const newOrder = e.target.checked
                          ? [...formData.bootOrder, 'network']
                          : formData.bootOrder.filter(item => item !== 'network');
                        setFormData({ ...formData, bootOrder: newOrder });
                      }}
                    />
                    网络
                  </label>
                </div>
              </div>

              <div className="form-group">
                <label>
                  <input
                    type="checkbox"
                    checked={formData.autostart}
                    onChange={(e) => setFormData({ ...formData, autostart: e.target.checked })}
                  />
                  自动启动
                </label>
              </div>

              <div className="form-group">
                <label>启动延迟 (秒)</label>
                <input
                  type="number"
                  min="0"
                  value={formData.bootDelay}
                  onChange={(e) => setFormData({ ...formData, bootDelay: parseInt(e.target.value) || 0 })}
                />
              </div>

              <div className="form-group">
                <label>引导加载器</label>
                <select
                  value={formData.loader}
                  onChange={(e) => setFormData({ ...formData, loader: e.target.value })}
                >
                  <option value="uefi">UEFI</option>
                  <option value="bios">BIOS</option>
                </select>
              </div>

              <div className="form-group">
                <label>图形设备</label>
                <select
                  value={formData.graphics}
                  onChange={(e) => setFormData({ ...formData, graphics: e.target.value })}
                >
                  <option value="vnc">VNC</option>
                  <option value="spice">SPICE</option>
                </select>
              </div>
            </div>
          );
        }
        // 对于其他方法，跳过此步骤
        return null;

      default:
        return (
          <div className="step-content">
            <h3>步骤 {currentStep}</h3>
            <p>此步骤的配置界面正在开发中...</p>
          </div>
        );
    }
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay">
      <div className="modal-content">
        <div className="modal-header">
          <h2>创建虚拟机向导</h2>
          <button onClick={onClose} className="close-button">×</button>
        </div>

        <div className="wizard-progress">
          <div className="step-indicator">
            {[...Array(getActualSteps())].map((_, index) => (
              <div
                key={index}
                className={`step ${index + 1 === currentStep ? 'active' : ''} ${index + 1 < currentStep ? 'completed' : ''}`}
              >
                {index + 1}
              </div>
            ))}
          </div>
        </div>

        <div className="modal-body">
          {renderStep()}

          {errors.submit && (
            <div className="error-message">
              {errors.submit}
            </div>
          )}
        </div>

        <div className="modal-footer">
          <button onClick={onClose} className="btn-secondary">取消</button>
          <div className="button-group">
            <button
              onClick={handlePrevious}
              disabled={currentStep === 1}
              className="btn-secondary"
            >
              上一步
            </button>
            <button
              onClick={handleNext}
              disabled={isSubmitting}
              className="btn-primary"
            >
              {currentStep === getActualSteps() ? '创建' : '下一步'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CreateVMWizardV2;